<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户促销模型
 * @author www.dingwei.cn
 */

class ConsumerPostalCardModel extends MY_Model{
	
	public $tbPostalCard = 'admin_postal_card'; //平台红包
	public $tbPostalCardLog = 'consumer_postal_card_log';//消费者记录
    public $tbUser = 'consumer'; // 用户
    public $tbOrder = 'consumer_order'; // 订单
    public $tbMerchantShop = 'merchant_shop'; //
    public $tbMerchantBonus = 'merchant_bonus'; //


    /**
     * 保存
     */
    public function saveBatch($data, $key =''){
        if(!$data) return false;
      if ($key == 'order_id'){
            $this->db->where('order_id', $key);
            $query = $this->updateBatch($this->tbPostalCardLog, $data);
            return $query === false ? false : true;
        }elseif ($key == 'id'){
            return $this->updateBatch($this->tbPostalCardLog, $data, 'id');
        }
        else{
            return $this->insertBatch($this->tbPostalCardLog, $data);
        }
    }

    /**
	 * 获取包邮卡记录
	 * @param integer $consumerId 消费者id
	 * @param number $page	分页
	 * @param number $status	1-未使用 2-使用 3-已过期
	 * @return array|array[]|number[]|unknown[]
	 */
	public function appGetBonusLogList($consumerId,$status,$page = 1,$total = FALSE,$wx = false, $all = false){
// 		echo strtotime('2017-12-31');
		$this->db
		->select('log.id,b.name,log.money,log.addtime,log.userendtime as use_end_time,log.status')
		->join($this->tbPostalCard.' b','b.id = log.postal_card_id','left')
		->where('log.consumer_id',$consumerId) //消费者
        ->where('b.status != 1');
		
		if ($status == 1){
			//未使用 未过期
			$this->db
			->where('log.status',1)//状态
			->where('log.userendtime >',time());//未过期
		}else if($status == 2){
			//已使用
			$this->db->where('log.status',2);//状态 
		}elseif ($status == 3){
			//过期
			$this->db
			->where('log.status',1)//未使用
			->where('log.userendtime <=',time());//过期
		}


		//只获取数量---------------------------------------------
		if ($total){

			return $this->count($this->tbPostalCardLog.' log');

		}
        //获取列表---------------------------------------------
        if($all){
            $tA = $this->getAll($this->tbPostalCardLog.' log');
            $tA['list'] = $tA;
        }else{
            $tA = $this->appPage($this->tbPostalCardLog.' log', $page);
        }

        $tA = $tA['list'];
//		$wxData[] = array('title' => '暂不使用','value' => [0, 0.00]);
        $wxData = array();
		foreach ($tA as $k=>$v){
			$tA[$k]['time'] = "0";
			if ($status == 1){
				$t = (string)floor(($v['use_end_time'] - time())/3600/24);
                $tA[$k]['time'] = $t.'天';
			}
			elseif ($status == 3){
				$tA[$k]['status'] = "3";
			}
			$tA[$k]['money'] = (string)(round($v['money'],1));
//            $wxData[] =  array('title' => $v['money'],'value' => [$v['id'], $v['money']]);
            $wxData[] =  array('title' => $v['name'].'('.$v['money'].')','value' => [$v['id'], $v['money']]);
		}
		
		return $wx == true?$wxData:$tA;
	}

	public function getUserPostcardLogList($consumerId,$status=0){
		$this->db
		->select('log.id,b.name,log.money,log.addtime,log.userendtime as use_end_time,log.status')
		->join($this->tbPostalCard.' b','b.id = log.postal_card_id','left')
		->where('log.consumer_id',$consumerId) //消费者
        ->where('b.status != 1');
		if ($status == 1){
			//未使用 未过期
			$this->db
			->where('log.status',1)//状态
			->where('log.userendtime >',time());//未过期
		}else if($status == 2){
			//已使用
			$this->db->where('log.status',2);//状态
		}elseif ($status == 3){
			//过期
			$this->db
			->where('log.status',1)//未使用
			->where('log.userendtime <=',time());//过期
		}
        //获取列表---------------------------------------------
        $tA = $this->pagination($this->tbPostalCardLog.' log');
		return $tA;
	}

    /**
     * 查看红包详情
     * @param $id
     * @return array
     * @author heyu
     */
    public function getInfo($id){
        if (!$id){
            return array();
        }
        $this->db->where(array('id' => $id));
        $tA = $this->getOne($this->tbPostalCard);
        $tA['use_start_time'] = dateFormat($tA['use_start_time']);
        $tA['use_end_time'] = dateFormat($tA['use_end_time']);
        return $tA;
    }

    public function getCard($data){
        if (!$data){
            return array();
        }
        $this->db->where($data);
        $tA = $this->getOne($this->tbPostalCard);
        return $tA;
    }

    /**
     * 批量获取包邮卡
     * @param array $bonusIds       红包ids
     * @param int   $consumerId     消费者id
     * @return array
     * @author zyl
     */
    public function getInfoIds($bonusIds,$consumerId = 0){
    	
    	if ( ! $bonusIds && ! $consumerId){
    		return array();
    	}
    	if ($consumerId){
    		$this->db->where('log.consumer_id',$consumerId);
    	}
    	
    	$this->db->select('log.id,log.money')
    	->join($this->tbPostalCard.' b','b.id=log.postal_card_id','left')
    	->where('log.begintime <=',time())//当前时间大于等雨开始时间
    	->where('log.userendtime >',time())//当前时间小于结束时间
    	->where('log.status',1)//未使用过
    	->where_in('log.id',$bonusIds);
    	
    	$tA = $this->getAll($this->tbPostalCardLog.' log');
 
    	$tData = array();
    	foreach ($tA as $k=>$v){
    		$tData[$v['id']] = $v;
    	}
    	return $tData;
    }

    /**
     * 获取红包总成本
     * @param int $startTime
     * @param int $endTime
     * @param int $page
     * @param int $pageNumber
     * @return array
     * @author heyu
     */
    public function getTotalBonusLog($startTime = 0, $endTime = 0, $page = 0, $pageNumber = 0){
        if ($startTime){
            $this->db->where('addtime >= '.$startTime);
        }
        if ($endTime){
            $this->db->where('addtime < '.$endTime);
        }
        $this->db->select('sum(money) as money,FROM_UNIXTIME(addtime,"%Y-%m") as time')
            ->where(array('status' => 2))
            ->group_by('time');
        $data = array();
        if ($page && $pageNumber) {
            $tA = $this->appPage($this->tbBonusLog, $page, false, $pageNumber);
            if (!empty($tA['list'])){
                foreach ($tA['list'] as $v){
                    $data[$v['time']] = $v;
                }
            }
        }else{
            $tA = $this->pagination($this->tbBonusLog);
            if (!empty($tA['data'])){
                foreach ($tA['data'] as $v){
                    $data[$v['time']] = $v;
                }
            }
        }

        unset($tA);
        return $data;
    }

    /**
     * 获取红包状态
     * @param $key
     * @param bool $show
     * @return array|mixed|string
     * @author heyu
     */
    public function getLogStatus($key, $show = false){
        $config = array(1 => '未使用', 2 => '使用');
        if( ! $key){
            return $config;
        }

        if($key && ! isset($config[$key])){
            return '';
        }

        if( ! $show){
            return $config[$key];
        }


        if($key == 1){
            return '<span class="label label-danger">'.$config[$key].'</span>';
        }else if($key == 2){
            return '<span class="label label-success">'.$config[$key].'</span>';
        }

        return'';
    }

    /**
     * 统计包邮卡
     * @param int $page
     * @param int $pageNumber
     * @return array
     */
    public function getStatisticsLog($page = 0, $pageNumber = 0){
        $timeGap = trim(get('timegap'));
        $type = (int)get('type');
        if (!isset($timeGap)){
            // 最近1个月
            $startTime = strtotime("-1 month");
            $endTime = 0;
        }else{
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]);
            $endTime = strtotime('+1 day', $endTime);
        }

        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($type){
            $this->db->where('b.type >= '.$type);
        }
        if ($startTime){
            $this->db->where('b.addtime >= '.$startTime);
        }
        if ($endTime){
            $this->db->where('b.addtime < '.$endTime);
        }

        if ($iSortCol_0 == 1){
            $this->db->order_by('b.money', $sSortDir_0); // 红包金额
        }else if($iSortCol_0 == 2){
            $this->db->order_by('send_number', $sSortDir_0); // 发布数量
        }else if($iSortCol_0 == 3){
            $this->db->order_by('used', $sSortDir_0); // 使用数量
        }else if($iSortCol_0 == 4){
            $this->db->order_by('not_used', $sSortDir_0); // 未使用数量
        }else if($iSortCol_0 == 5){
            $this->db->order_by('use_end', $sSortDir_0); // 失效数量
        }else if($iSortCol_0 == 6){
            $this->db->order_by('used_money', $sSortDir_0); // 使用金额
        }else if($iSortCol_0 == 7){
            $this->db->order_by('total_money', $sSortDir_0); // 红包金额
        }else if($iSortCol_0 == 8){
            $this->db->order_by('b.use_end_time', $sSortDir_0); // 截至时间
        }else if($iSortCol_0 == 9){
            $this->db->order_by('b.addtime', $sSortDir_0); // 发放时间
        }
        $t = strtotime(date('Y-m-d', time()));
        $this->db->select('b.name,b.money,b.use_end_time,count(bl.id) as send_number,count(if(bl.status = 1, bl.status, null)) as not_used,
        count(if(bl.status = 2, bl.status, null)) as used,sum(if(bl.status = 2, bl.money, null)) as used_money,
        sum(bl.money) as total_money,b.addtime,count(if(bl.status = 1 and b.status = 2 and b.use_end_time < '.$t.', bl.id, null)) as use_end')
            ->join($this->tbPostalCardLog.' bl', 'b.id=bl.postal_card_id')
            ->where('b.status', 2)
            ->group_by('b.id');
        if ($page && $pageNumber) {
            $tA = $this->appPage($this->tbPostalCard.' b', $page, false, $pageNumber);
            return $tA['list'];
        }else{
            return $this->pagination($this->tbPostalCard.' b');
        }

    }

    /**
     * 获取用户红包个数
     * @param int           $userId         用户id
     * @return array|int
     */
    public function getConsumerBonusNumber($userId){
        if (!$userId){
            return 0;
        }
        $time = time();
        $this->db->join($this->tbBonus.' b', 'b.id=bl.bonus_id')
            ->where(array('bl.consumer_id' => $userId, 'bl.status' => 1))
            ->where("b.use_start_time <= $time and b.use_end_time >= $time");
        return $this->count($this->tbBonusLog.' bl');
    }

    public function statisticsLogCount($ids){
        if(!$ids)return array();
        $this->db->select('bl.postal_card_id,count(bl.id) as count')
            ->join($this->tbPostalCard.' b', 'b.id=bl.postal_card_id')
            ->where_in('b.id', $ids)
            ->group_by('bl.postal_card_id');

        $data = $this->getAll($this->tbPostalCardLog.' bl');

        $tData = [];
        foreach ($data as $v){
            $tData[$v['postal_card_id']] = $v['count'];
        }

        return $tData;
    }
}